package com.itheima.controller;

import com.itheima.domian.Role;
import com.itheima.domian.UserInfo;
import com.itheima.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService iUserService;


    @RequestMapping("/addRoleToUser.do")
    public String addRoleToUser(
            @RequestParam(name = "userId", required = true) String userId,
            @RequestParam(name = "ids", required = true) String[] roleIds) throws Exception {
        iUserService.addRoleToUser(userId, roleIds);
        return "redirect:findAll.do";
    }


    //查询用户以及用户可以添加的角色
    @RequestMapping("/findUserByIdAndAllRole.do")
    public ModelAndView findUserByIdAndAllRole(@RequestParam(name = "id", required = true) String userid) throws Exception {
        ModelAndView mv = new ModelAndView();
//        根据用户id查询用户
        UserInfo userInfo = iUserService.findById(userid);
//        根据用户id查询可以添加的角色
        List<Role> otherRoleList = iUserService.findOtherRoles(userid);
//        iUserService.findUserByIdAndRole();
        mv.addObject("user", userInfo);
        mv.addObject("roleList", otherRoleList);
        mv.setViewName("user-role-add");
        return mv;
    }


    @RequestMapping("/findById.do")
    public ModelAndView findById(String id) throws Exception {
        ModelAndView mv = new ModelAndView();
        UserInfo userInfo = iUserService.findById(id);
        mv.addObject("user", userInfo);
        mv.setViewName("user-show3");
        return mv;
    }


    @RequestMapping("/save.do")
    @PreAuthorize("authentication.principal.username == 'le' ")
    public String save(UserInfo userInfo) throws Exception {
        iUserService.save(userInfo);
        return "redirect:findAll.do";
    }

    @RequestMapping("findAll.do")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ModelAndView findAll() throws Exception {
        ModelAndView mv = new ModelAndView();
        List<UserInfo> userInfoLists = iUserService.findAll();
        mv.addObject("userList", userInfoLists);
        mv.setViewName("user-list");

        return mv;
    }
}
